const app = getApp()
var dateUtils = require('../utils/dateUtil.js');
import {
  getStaticImgUrl,
  API_DOMAIN
} from '../utils/api.config'

Page({

  /**
   * 页面的初始数据
   */
  data: {
    cardGroundUrl: '../images/new/banner.png',
    modal: null,
    userData: {},
    stuIndex: 0,
    userInfo: [],
    dataInfo: {},
    taskList: [],
    equipmentList: [], //设备记录
    selectContentIndex: 0
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    wx.setNavigationBarTitle({
      title: "智能跳绳"
    })

    this.initView()
  },

  initView() {
    const userInfo = wx.getStorageSync('userData');
    const stuIndex = wx.getStorageSync('stuIndex');
    const data = userInfo.list[stuIndex]
    this.setData({
      userData: data,
      stuIndex: stuIndex,
      userInfo: userInfo
    })


    this.getData()
    this.getTaskData()
    this.getMineJumList()

  },


  //我的跳绳
  goJumpJob() {
    wx.navigateTo({
      url: '/packJumpRope/mineJump'
    })
  },


  getData() {
    wx.showLoading({
      title: '加载中...',
      icon: 'none',
    })
    var id = this.data.userData.studentId
    app.api.skipRopeInfo().then(rest => {
        wx.hideLoading()
        console.log('2获取转换后数据skipRopeInfo', JSON.stringify(rest))
        if (rest && rest.success) {

          var data = rest.data;

          data.topList = this.conversionHistory(data.topList)
          this.setData({
            dataInfo: data
          })
        } else {
          var data = {
            topList: [null, null, null]
          };
          console.log('3获取转换后数据skipRopeInfo', JSON.stringify(data))
          data.topList = this.conversionHistory(data.topList)
          this.setData({
            dataInfo: data
          })
        }
      })
      .catch(r => {
        wx.hideLoading()
        var data = {
          topList: [null, null, null]
        };
        console.log('获取转换后数据skipRopeInfo', JSON.stringify(data))
        data.topList = this.conversionHistory(data.topList)
        this.setData({
          dataInfo: data
        })
        wx.showToast({
          title: '网络异常，请稍后重试！',
          icon: 'none',
          duration: 2000,
          mask: true
        })
      })

  },
  getTaskData() {

    wx.showLoading({
      title: '加载中...',
      icon: 'none',
    })
    var data = {
      pageNo: 1,
      pageSize: 2,
      //startTime:dateUtils.formatDataTime(new Date()), 
    }
    app.api.stuQueryTaskRopeList(data).then(rest => {
        wx.hideLoading()

        if (rest && rest.success) {

          var data = rest.data.records;
          this.setData({
            taskList: data
          })
        } else {

        }
      })
      .catch(r => {
        wx.hideLoading()
        console.error(r)
        wx.showToast({
          title: '网络异常，请稍后重试！',
          icon: 'none',
          duration: 2000,
          mask: true
        })
      })
  },
  conversionHistory(list) {
    var dataList = []
    if (list) {
      for (var i = 0; i < list.length; i++) {
        var item = list[i];
        if (i == 0) {
          if (item) {
            item.isPlay = true
          } else {
            item = {}
            item.model = i + 1
          }
          item.img = getStaticImgUrl('/new/minute_time.png')
          item.name = '1分钟倒计时'
          dataList.push(item)
        } else if (i == 1) {

          if (item) {
            item.isPlay = true


          } else {
            item = {}

            item.model = i + 1
          }
          item.img = getStaticImgUrl('/new/counter.png')
          item.name = '200个倒计数'
          dataList.push(item)
        } else if (i == 2) {
          if (item) {
            item.isPlay = true


          } else {
            item = {}

            item.model = i + 1
          }
          item.name = '自由跳'
          item.img = getStaticImgUrl('/new/freedom_jump.png')
          dataList.push(item)
        }


      }
    }
    return dataList
  },
  //小孩选择弹框回调
  change(e) {

    var that = this
    var vIndex = e.detail.index
    var stuName = e.detail.name + "同学"
    let studentId = that.data.userInfo.list[vIndex].studentId

    this.updateStudentId(studentId, vIndex)
  },

  //切换学生
  updateStudentId(studentId, vIndex) {
    var that = this;
    wx.showLoading({
      title: '切换中...',
      icon: 'none',
    })
    wx.request({
      url: API_DOMAIN + 'app/appUser/updateStudentId/',
      data: studentId,
      method: 'POST',
      header: {
        'content-type': 'application/json', // 默认值
        'Authorization': wx.getStorageSync('tokenId')
      },
      success(res) {
        wx.setStorageSync('stuIndex', vIndex)
        that.initView()
        wx.showToast({
          title: '学生切换成功',
          icon: 'none',
          duration: 2000,
          mask: true
        })
      },
      complete() {
        wx.hideLoading()
      }
    })
  },

  //任务详情 
  goDetail(e) {
    wx.navigateTo({
      url: '/packJumpTask/parean/renwuxiangqing/renwuxiangqing?taskId=' + this.data.taskList[e.currentTarget.dataset.index].taskId,
    })
  },
  //跳转setting
  goSetting() {
    wx.navigateTo({
      url: '/packJumpRope/setting'
    })
  },

  //开始练习跳绳
  startJump(e) {
    var item = e.currentTarget.dataset.info
    var that = this;
    var muList = []
    if (!this.data.equipmentList || this.data.equipmentList.length <= 0) {
      this.modal.showModal({
        title: '温馨提示',
        modalType: 0,
        content: '您暂无绑定跳绳设备，请先进行绑定',
        topImageUrl: getStaticImgUrl('/new/alert_result.png'),
        complete: (res) => {
          if (res.cancel) {}
          if (res.confirm) {
            wx.navigateTo({
              url: '/packJumpRope/addMineList',
            })

          }
        }
      })

      return;
    }



    this.modal.showModal({
      title: '温馨提示',
      modalType: 0,
      content: '确定进行跳绳练习吗？',
      topImageUrl: getStaticImgUrl('/new/alert_result.png'),
      complete: (res) => {
        if (res.cancel) {}
        if (res.confirm) {


          that.subMitStartJump(0, item.model)


        }
      }
    })

    return
    for (var i = 0; i < this.data.equipmentList.length; i++) {
      let item = this.data.equipmentList[i]
      muList.push(item.name)
    }
    //一根跳绳直接开始
    if (muList.length > 1) {
      this.modal.showModal({
        title: '跳绳选择',
        modalType: 3,
        contentList: muList,
        selectContentIndex: this.data.selectContentIndex,
        topImageUrl: getStaticImgUrl('/new/alert_result.png'),
        complete: (res) => {
          if (res.cancel) {}
          if (res.confirm) {
            var index = res.data.showData.selectContentIndex
            this.setData({
              selectContentIndex: index
            })
            var tempItem = this.data.equipmentList[index]
            that.subMitStartJump(tempItem.imei, item.model)

          }
        }
      })
    } else if (muList.length == 1) {
      that.subMitStartJump(this.data.equipmentList[0].imei, item.model)
    } else {
      wx.showToast({
        title: '请选绑定智能跳绳',
        icon: 'none',
        duration: 1500,
        mask: true
      })
    }



  },
  subMitStartJump(imei, skipmode) {

    var data = {
      skipmode: skipmode,
      taskId: 0
      // imei: imei
    }
    wx.showLoading({
      title: '提交中...',
    })
    let that = this;
    console.log('跳绳提交数据=', JSON.stringify(data))
    app.api.skipMode(data).then(rest => {
        wx.hideLoading()
        if (rest && rest.success) {
          console.log('跳绳成功', JSON.stringify(rest))
          wx.showToast({
            title: '跳绳启动成功，请开始您的跳绳',
            icon: "none"
          })
          setTimeout(() => {
            that.initView()

          }, 1500)

        } else {
          console.log('跳绳失败', JSON.stringify(rest))
        }
      })
      .catch(r => {
        wx.hideLoading()
        console.error(r)
        wx.showToast({
          title: '网络异常，请稍后重试！',
          icon: 'none',
          duration: 2000,
          mask: true
        })
      })
  },
  getMineJumList() {
    wx.showLoading({
      title: '加载中...',
      icon: 'none',
    })
    app.api.mySkipRope(this.data.userData.studentId).then(rest => {
        wx.hideLoading()

        if (rest && rest.success) {
          var list = rest.data
          console.log('获取转换后数据', JSON.stringify(list))
          wx.setStorageSync('mineJumList', list);
          this.setData({
            equipmentList: list
          })
        } else {
          wx.showToast({
            title: rest.errMsg || '网络异常，请稍后重试！！',
            icon: 'none',
            duration: 2000,
            mask: true
          })
        }
      })
      .catch(r => {
        console.error(r)
        wx.showToast({
          title: '网络异常，请稍后重试！',
          icon: 'none',
          duration: 2000,
          mask: true
        })
      })

  },


  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {
    this.modal = this.selectComponent("#modal")

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    this.initView()
    console.log("接口==" + this.data.stuIndex);
    this.selectComponent("#select").setViewData(this.data.stuIndex)

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})